﻿using NLog;

namespace Q.Spider.Common
{
    public class LogHelper
    {
        private static bool IsInit = false;
        public static Logger Logger
             => IsInit ? LogManager.GetCurrentClassLogger() : Init();


        private static Logger Init()
        {
            var config = new NLog.Config.LoggingConfiguration();
            config.AddTarget("console", new NLog.Targets.ConsoleTarget()
            {
                Layout = new NLog.Layouts.SimpleLayout("${longdate}|${level}|${message}|${callsite}|${machinename} |${all-event-properties} ${exception:format=tostring}")
                {

                }
            });

            config.AddTarget("file", new NLog.Targets.FileTarget()
            {
                FileName = new NLog.Layouts.SimpleLayout("${basedir}/logs/${shortdate}.txt"),
                Layout = new NLog.Layouts.SimpleLayout("${longdate}|${level}|${message}|${callsite}|${machinename} |${all-event-properties} ${exception:format=tostring}")
                ,
                MaxArchiveDays = 30
            });

            config.AddRule(LogLevel.Info, LogLevel.Fatal, "console");
            config.AddRule(LogLevel.Info, LogLevel.Fatal, "file");

            LogManager.Configuration = config;
            IsInit = true;
            return LogManager.GetCurrentClassLogger();
        }

        /// <summary>
        /// 设置日志输出级别
        /// "1" = 所有内容都输出 包括 Trace Debug Info
        /// "2" = Warn 及以上才输出 Warn Error Fatal
        /// </summary>
        /// <param name="lv"></param>
        public static void SetLogOutputLevel(string lv)
        {
            //LogManager.Configuration.LoggingRules.Clear();


            foreach (var item in LogManager.Configuration.LoggingRules)
            {
                if (typeof(NLog.Targets.ConsoleTarget).Equals(item.Targets[0].GetType()))
                {
                    if (lv == "2")
                    {
                        item.SetLoggingLevels(LogLevel.Warn, LogLevel.Fatal);
                    }
                    else
                    {
                        item.SetLoggingLevels(LogLevel.Trace, LogLevel.Fatal);
                    }
                }
                LogManager.ReconfigExistingLoggers();
            }
        }


    }
}